#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
彩票中奖结果自动查询工具主程序
"""

import sys
import json
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QAction, QFileDialog, QMessageBox
from PyQt5.QtGui import QIcon
from ui_components import LotteryHistoryWidget, UserTicketManagerWidget, LotteryDetailsWidget
from data_manager import DataManager
from matcher import NumberMatcher

class MainWindow(QMainWindow):
    """
    主窗口类
    """
    def __init__(self):
        super().__init__()
        self.data_manager = DataManager()
        self.matcher = NumberMatcher()
        self.init_ui()
        
    def init_ui(self):
        # 设置窗口属性
        self.setWindowTitle("彩票中奖结果自动查询工具")
        self.setGeometry(100, 100, 1000, 700)
        
        # 创建菜单栏
        self.create_menu()
        
        # 创建标签页组件
        self.tab_widget = QTabWidget()
        
        # 创建各个功能组件
        self.lottery_history_widget = LotteryHistoryWidget()
        self.user_ticket_manager_widget = UserTicketManagerWidget()
        self.lottery_details_widget = LotteryDetailsWidget()
        
        # 添加标签页
        self.tab_widget.addTab(self.lottery_history_widget, "开奖历史")
        self.tab_widget.addTab(self.user_ticket_manager_widget, "号码管理")
        self.tab_widget.addTab(self.lottery_details_widget, "彩票详情")
        
        # 设置中心组件
        self.setCentralWidget(self.tab_widget)
        
        # 创建状态栏
        self.statusBar().showMessage("就绪")
    
    def create_menu(self):
        # 创建菜单栏
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu('文件')
        
        # 退出动作
        exit_action = QAction('退出', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 数据菜单
        data_menu = menubar.addMenu('数据')
        
        # 导入数据动作
        import_action = QAction('导入数据', self)
        import_action.triggered.connect(self.import_data)
        data_menu.addAction(import_action)
        
        # 导出数据动作
        export_action = QAction('导出数据', self)
        export_action.triggered.connect(self.export_data)
        data_menu.addAction(export_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu('帮助')
        
        # 关于动作
        about_action = QAction('关于', self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def import_data(self):
        # 导入数据功能
        file_path, _ = QFileDialog.getOpenFileName(self, "导入数据", "", "JSON Files (*.json)")
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                # 判断导入的数据类型
                if isinstance(data, list) and len(data) > 0:
                    if "type" in data[0] and "numbers" in data[0]:
                        # 可能是彩票数据
                        if "date" in data[0]:
                            # 可能是开奖历史或用户号码
                            reply = QMessageBox.question(self, '导入确认', 
                                                       '检测到彩票数据，是否导入为开奖历史数据？\n选择"是"导入为开奖历史，选择"否"导入为用户号码，选择"取消"取消导入',
                                                       QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
                            
                            if reply == QMessageBox.Yes:
                                # 导入为开奖历史
                                self.data_manager.save_lottery_history(data, "lottery_history.json")
                                QMessageBox.information(self, "成功", "开奖历史数据导入成功")
                            elif reply == QMessageBox.No:
                                # 导入为用户号码
                                self.data_manager.save_user_tickets(data, "user_tickets.json")
                                QMessageBox.information(self, "成功", "用户号码数据导入成功")
                        else:
                            # 默认导入为用户号码
                            self.data_manager.save_user_tickets(data, "user_tickets.json")
                            QMessageBox.information(self, "成功", "用户号码数据导入成功")
                    else:
                        QMessageBox.warning(self, "格式错误", "数据格式不正确")
                else:
                    QMessageBox.warning(self, "格式错误", "数据格式不正确")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"导入失败: {str(e)}")
    
    def export_data(self):
        # 导出数据功能
        file_path, _ = QFileDialog.getSaveFileName(self, "导出数据", "", "JSON Files (*.json)")
        if file_path:
            try:
                # 询问用户要导出的数据类型
                reply = QMessageBox.question(self, '导出确认', 
                                           '选择要导出的数据类型：\n"是"导出开奖历史，"否"导出用户号码，"取消"取消导出',
                                           QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
                
                if reply == QMessageBox.Yes:
                    # 导出开奖历史
                    data = self.data_manager.load_lottery_history()
                    with open(file_path, 'w', encoding='utf-8') as f:
                        json.dump(data, f, ensure_ascii=False, indent=2)
                    QMessageBox.information(self, "成功", "开奖历史数据导出成功")
                elif reply == QMessageBox.No:
                    # 导出用户号码
                    data = self.data_manager.load_user_tickets()
                    with open(file_path, 'w', encoding='utf-8') as f:
                        json.dump(data, f, ensure_ascii=False, indent=2)
                    QMessageBox.information(self, "成功", "用户号码数据导出成功")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"导出失败: {str(e)}")
    
    def show_about(self):
        # 显示关于信息
        QMessageBox.about(self, "关于", "彩票中奖结果自动查询工具\n版本: 1.0.0\n\n一个帮助您管理彩票号码并自动查询中奖结果的工具。")

def main():
    # 创建应用实例
    app = QApplication(sys.argv)
    
    # 创建主窗口
    main_window = MainWindow()
    
    # 显示主窗口
    main_window.show()
    
    # 运行应用
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()